<!-- 修改文件：src/components/FriendSidebar.vue -->
<template>
  <div class="friend-sidebar">
    <div class="sidebar-header">
      <h3>好友列表</h3>
      <button @click="showAddFriendDialog = true">添加好友</button>
      <button
          class="refresh-btn"
          @click="refreshFriendList"
          :disabled="loading"
      >
        {{ loading ? '刷新中...' : '刷新' }}
      </button>
    </div>

    <!-- 添加好友对话框 -->
    <div v-if="showAddFriendDialog" class="dialog-overlay">
      <div class="add-friend-dialog">
        <div class="dialog-header">
          <h3>添加好友</h3>
          <button class="close-btn" @click="closeDialog">&times;</button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label for="friendId">好友ID</label>
            <input
                id="friendId"
                v-model="newFriendId"
                type="text"
                placeholder="请输入好友ID"
            />
          </div>
          <div class="form-group">
            <label for="remark">备注信息</label>
            <input
                id="remark"
                v-model="newFriendRemark"
                type="text"
                placeholder="请输入备注信息（可选）"
            />
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="sendFriendRequest" :disabled="sendingRequest">
            {{ sendingRequest ? '发送中...' : '发送请求' }}
          </button>
        </div>
        <div v-if="requestError" class="error-message">{{ requestError }}</div>
      </div>
    </div>

    <div class="friend-list">
      <div class="search-box">
        <input
            v-model="searchQuery"
            placeholder="搜索好友..."
            @input="handleSearch"
        />
        <span class="search-icon">🔍</span>
      </div>

      <template v-if="error">
        <div class="error-message">
          {{ error }}
          <button @click="refreshFriendList">重试</button>
        </div>
      </template>

      <template v-else>
        <!-- 已同意好友 -->
        <div class="status-group">
          <div class="group-header" @click="toggleGroup('accepted')">
            <span>已同意好友</span>
            <span class="group-count">({{ filteredAcceptedFriends.length }})</span>
            <span class="toggle-icon">{{ groupStates.accepted ? '▼' : '▶' }}</span>
            <span v-if="totalUnreadAccepted > 0" class="unread-badge">{{ totalUnreadAccepted }}</span>
          </div>
          <div class="group-friends" v-show="groupStates.accepted">
            <div
                v-for="friend in filteredAcceptedFriends"
                :key="friend.id"
                class="friend-item"
                :class="{
                  'active': activeFriendId === friend.id,
                  'online': friend.online,
                  'offline': !friend.online,
                  'has-unread': friend.unread > 0
                }"
                @click="selectFriend(friend)"
            >
              <div class="friend-avatar">
                <span class="online-status"></span>
              </div>
              <div class="friend-info">
                <div class="friend-name">{{ friend.name }}</div>
                <div class="friend-status">
                  <template v-if="friend.online">在线</template>
                  <template v-else>{{ friend.lastSeen || '离线' }}</template>
                </div>
              </div>
              <div v-if="friend.unread > 0" class="unread-count">
                {{ friend.unread > 99 ? '99+' : friend.unread }}
              </div>
              <button
                  class="delete-btn"
                  @click.stop="confirmDeleteFriend(friend)"
                  title="删除好友"
              >
                ×
              </button>
            </div>
            <div v-if="filteredAcceptedFriends.length === 0" class="no-friends-in-group">
              无匹配好友
            </div>
          </div>
        </div>

        <!-- 待确认好友 -->
        <div class="status-group">
          <div class="group-header" @click="toggleGroup('pending')">
            <span>待确认好友</span>
            <span class="group-count">({{ filteredPendingFriends.length }})</span>
            <span class="toggle-icon">{{ groupStates.pending ? '▼' : '▶' }}</span>
          </div>
          <div class="group-friends" v-show="groupStates.pending">
            <div
                v-for="friend in filteredPendingFriends"
                :key="friend.id"
                class="friend-item pending"
            >
              <div class="friend-avatar">
                <span class="online-status"></span>
              </div>
              <div class="friend-info">
                <div class="friend-name">{{ friend.name }}</div>
                <div class="friend-status">待确认</div>
                <div class="friend-remark" v-if="friend.remark">备注: {{ friend.remark }}</div>
                <div class="friend-actions" v-if="friend.receiverId === authStore.userInfo.id">
                  <button
                      class="action-btn accept"
                      @click.stop="handleFriendRequest(friend.relationId, 1)"
                  >同意</button>
                  <button
                      class="action-btn reject"
                      @click.stop="handleFriendRequest(friend.relationId, 2)"
                  >拒绝</button>
                  <button
                      class="action-btn block"
                      @click.stop="handleFriendRequest(friend.relationId, 3)"
                  >拉黑</button>
                </div>
                <div v-else class="friend-status">
                  等待对方确认
                </div>
              </div>
            </div>
            <div v-if="filteredPendingFriends.length === 0" class="no-friends-in-group">
              无匹配好友
            </div>
          </div>
        </div>

        <!-- 已拒绝好友 -->
        <div class="status-group">
          <div class="group-header" @click="toggleGroup('rejected')">
            <span>已拒绝好友</span>
            <span class="group-count">({{ filteredRejectedFriends.length }})</span>
            <span class="toggle-icon">{{ groupStates.rejected ? '▼' : '▶' }}</span>
          </div>
          <div class="group-friends" v-show="groupStates.rejected">
            <div
                v-for="friend in filteredRejectedFriends"
                :key="friend.id"
                class="friend-item"
                @click="selectFriend(friend)"
            >
              <div class="friend-avatar">
                <span class="online-status"></span>
              </div>
              <div class="friend-info">
                <div class="friend-name">{{ friend.name }}</div>
                <div class="friend-status">已拒绝</div>
              </div>
              <div class="friend-actions" v-if="friend.receiverId === authStore.userInfo.id">
                <button
                    class="action-btn accept"
                    @click.stop="handleFriendRequest(friend.relationId, 1)"
                >同意</button>
              </div>
            </div>
            <div v-if="filteredRejectedFriends.length === 0" class="no-friends-in-group">
              无匹配好友
            </div>
          </div>
        </div>

        <!-- 已拉黑好友 -->
        <div class="status-group">
          <div class="group-header" @click="toggleGroup('blocked')">
            <span>已拉黑好友</span>
            <span class="group-count">({{ filteredBlockedFriends.length }})</span>
            <span class="toggle-icon">{{ groupStates.blocked ? '▼' : '▶' }}</span>
          </div>
          <div class="group-friends" v-show="groupStates.blocked">
            <div
                v-for="friend in filteredBlockedFriends"
                :key="friend.id"
                class="friend-item blocked"
                @click="selectFriend(friend)"
            >
              <div class="friend-avatar">
                <span class="online-status"></span>
              </div>
              <div class="friend-info">
                <div class="friend-name">{{ friend.name }}</div>
                <div class="friend-status">已拉黑</div>
              </div>
            </div>
            <div v-if="filteredBlockedFriends.length === 0" class="no-friends-in-group">
              无匹配好友
            </div>
          </div>
        </div>

        <div v-if="hasNoResults" class="no-friends">
          没有找到匹配的好友
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useChatSimpleStore } from '@/stores/chatSimpleStore.js'
import { useAuthStore } from '@/stores/modules/authStore.js'
import { useStorage } from '@vueuse/core'
import { chatAPI } from '@/api/chat/index.js'
import { ElMessageBox, ElMessage } from 'element-plus'

const emit = defineEmits(['select-friend'])

const chatStore = useChatSimpleStore()
const authStore = useAuthStore()
const searchQuery = ref('')
const activeFriendId = ref(null)
const loading = ref(false)
const error = ref(null)

// 添加好友相关状态
const showAddFriendDialog = ref(false)
const newFriendId = ref('')
const newFriendRemark = ref('')
const sendingRequest = ref(false)
const requestError = ref('')

// 使用本地存储保存分组展开状态
const groupStates = useStorage('friend-group-states', {
  accepted: true,
  pending: false,
  rejected: false,
  blocked: false
})

// 根据状态分类好友
const acceptedFriends = computed(() => {
  return chatStore.friendList.filter(friend => friend.status === 1)
})

const pendingFriends = computed(() => {
  return chatStore.friendList.filter(friend => friend.status === 0)
})

const rejectedFriends = computed(() => {
  return chatStore.friendList.filter(friend => friend.status === 2)
})

const blockedFriends = computed(() => {
  return chatStore.friendList.filter(friend => friend.status === 3)
})

// 计算已同意好友的总未读消息数
const totalUnreadAccepted = computed(() => {
  return acceptedFriends.value.reduce((total, friend) => total + (friend.unread || 0), 0)
})

// 过滤后的好友列表
const filterFriends = (friends) => {
  if (!searchQuery.value) return friends
  return friends.filter(friend =>
      friend.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
}

const filteredAcceptedFriends = computed(() => filterFriends(acceptedFriends.value))
const filteredPendingFriends = computed(() => filterFriends(pendingFriends.value))
const filteredRejectedFriends = computed(() => filterFriends(rejectedFriends.value))
const filteredBlockedFriends = computed(() => filterFriends(blockedFriends.value))

// 检查是否没有任何搜索结果
const hasNoResults = computed(() => {
  return searchQuery.value &&
      filteredAcceptedFriends.value.length === 0 &&
      filteredPendingFriends.value.length === 0 &&
      filteredRejectedFriends.value.length === 0 &&
      filteredBlockedFriends.value.length === 0
})

// 自动展开包含搜索结果的组
watch(searchQuery, (newVal) => {
  if (newVal) {
    if (filteredAcceptedFriends.value.length > 0) groupStates.value.accepted = true
    if (filteredPendingFriends.value.length > 0) groupStates.value.pending = true
    if (filteredRejectedFriends.value.length > 0) groupStates.value.rejected = true
    if (filteredBlockedFriends.value.length > 0) groupStates.value.blocked = true
  }
})

// 切换分组展开/折叠状态
const toggleGroup = (group) => {
  groupStates.value[group] = !groupStates.value[group]
}

// 刷新好友列表
const refreshFriendList = async () => {
  try {
    loading.value = true
    error.value = null
    await chatStore.fetchFriendList()
  } catch (err) {
    error.value = err.message || '刷新好友列表失败'
  } finally {
    loading.value = false
  }
}

//删除好友
const confirmDeleteFriend = async (friend) => {
  try {
    const confirm = await ElMessageBox.confirm(
        `确定要删除好友 ${friend.name} 吗？此操作不可撤销。`,
        '删除好友确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    if (confirm) {
      loading.value = true
      await chatAPI.deleteFriend(friend.relationId)
      ElMessage.success(`已删除好友 ${friend.name}`)
      await refreshFriendList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除好友失败')
    }
  } finally {
    loading.value = false
  }
}
// 选择好友
const selectFriend = (friend) => {
  // 不允许选择待确认或已拉黑的好友
  if (friend.status === 0 || friend.status === 3) return

  activeFriendId.value = friend.id
  emit('select-friend', friend)

  // 清除该好友的未读消息计数
  chatStore.clearUnreadCount(friend.id)
}

// 处理好友请求
const handleFriendRequest = async (relationId, status) => {
  console.group('处理好友请求 - 调试信息')
  try {
    console.log('开始处理好友请求', {
      relationId,
      status,
      timestamp: new Date().toISOString()
    })

    loading.value = true
    console.log('设置loading状态为true')

    console.log('准备调用chatAPI.responseFriend，参数:', {
      relationId,
      status
    })

    const response = await chatAPI.responseFriend({
      relationId,
      status
    })

    console.log('API调用成功，响应数据:', response)

    const actionText = status === 1 ? '已同意好友请求' :
        status === 2 ? '已拒绝好友请求' : '已拉黑该用户'

    console.log('准备显示成功消息:', actionText)
    ElMessage.success(actionText)

    console.log('准备刷新好友列表...')
    await refreshFriendList()
    console.log('好友列表刷新完成')

  } catch (err) {
    console.error('处理好友请求时发生错误:', {
      error: err,
      relationId,
      status,
      stack: err.stack
    })

    let errorMessage = '处理好友请求失败'
    if (err.response) {
      console.error('错误响应详情:', {
        status: err.response.status,
        data: err.response.data,
        headers: err.response.headers
      })
      errorMessage = err.response.data?.message || errorMessage
    } else if (err.request) {
      console.error('请求已发出但无响应:', err.request)
      errorMessage = '服务器无响应'
    } else {
      console.error('请求配置错误:', err.config)
      errorMessage = err.message || errorMessage
    }

    console.log('准备显示错误消息:', errorMessage)
    ElMessage.error(errorMessage)

  } finally {
    loading.value = false
    console.log('重置loading状态为false')
    console.groupEnd()
  }
}

// 处理搜索输入 - 添加防抖
let searchTimeout = null
const handleSearch = () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    // 搜索逻辑已通过计算属性自动处理
  }, 300)
}

// 关闭对话框
const closeDialog = () => {
  showAddFriendDialog.value = false
  newFriendId.value = ''
  newFriendRemark.value = ''
  requestError.value = ''
}

// 发送好友请求
const sendFriendRequest = async () => {
  if (!newFriendId.value) {
    requestError.value = '请输入好友ID'
    return
  }

  // 检查是否已在好友列表或待确认列表中
  const isAlreadyFriend = chatStore.friendList.some(
      friend => friend.id === newFriendId.value && (friend.status === 0 || friend.status === 1)
  )

  if (isAlreadyFriend) {
    requestError.value = '好友列表或待确认好友列表中已存在该好友'
    return
  }

  try {
    sendingRequest.value = true
    requestError.value = ''

    const response = await chatAPI.addFriend({
      requesterId: authStore.userInfo.id,
      receiverId: newFriendId.value,
      remark: newFriendRemark.value
    })

    // 请求成功后刷新好友列表
    await refreshFriendList()
    closeDialog()
    ElMessage.success('请求成功')
  } catch (err) {
    requestError.value = err.message || '发送好友请求失败'
  } finally {
    sendingRequest.value = false
  }
}

// 组件挂载时获取好友列表
onMounted(() => {
  if (chatStore.friendList.length === 0) {
    refreshFriendList()
  }

  // 移动端默认只展开已同意好友
  if (window.innerWidth < 768) {
    groupStates.value = {
      accepted: true,
      pending: false,
      rejected: false,
      blocked: false
    }
  }
})
</script>

<style scoped>
/* 原有样式保持不变，新增以下样式 */
.friend-actions {
  display: flex;
  gap: 5px;
  margin-top: 5px;
}

.action-btn {
  padding: 2px 6px;
  font-size: 0.7em;
  border-radius: 3px;
  cursor: pointer;
  border: none;
}

.action-btn.accept {
  background-color: #67c23a;
  color: white;
}

.action-btn.reject {
  background-color: #f56c6c;
  color: white;
}

.action-btn.block {
  background-color: #909399;
  color: white;
}

.friend-remark {
  font-size: 0.7em;
  color: #666;
  margin-top: 2px;
}

/* 原有样式保持不变 */
.friend-sidebar {
  width: 250px;
  background-color: #ffffff;
  color: #01060c;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.sidebar-header {
  padding: 15px;
  background-color: #ffffff;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.search-box {
  padding: 10px;
  position: relative;
  flex-shrink: 0;
}

.search-box input {
  width: 100%;
  padding: 8px 30px 8px 10px;
  border-radius: 4px;
  border: none;
  background-color: #f4f4f4;
  color: #1e1d1d;
}

.search-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0.6;
}

.friend-list {
  flex: 1;
  overflow-y: auto;
}

.status-group {
  margin-bottom: 10px;
}

.group-header {
  padding: 10px 15px;
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eee;
  position: relative;
}

.group-header:hover {
  background-color: #f0f0f0;
}

.group-count {
  margin-left: 5px;
  color: #5c5d5d;
  font-size: 0.8em;
}

.toggle-icon {
  margin-left: auto;
  font-size: 0.8em;
  color: #666;
}

.unread-badge {
  position: absolute;
  right: 35px;
  background-color: #e74c3c;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 0.7em;
  min-width: 18px;
  text-align: center;
}

.group-friends {
  max-height: 300px;
  overflow-y: auto;
  transition: all 0.3s ease;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 8px 15px;
  cursor: pointer;
  position: relative;
}

.friend-item:hover {
  background-color: rgb(242, 242, 242);
}

.friend-item.active {
  background-color: #d6e4ff;
}

.friend-item.has-unread {
  background-color: #f8f4ff;
}

.friend-item.online .friend-status {
  color: #2ecc71;
}

.friend-item.offline .friend-status {
  color: #8e9b9c;
}

.friend-item.pending {
  opacity: 0.6;
}

.friend-item.pending .friend-status {
  color: #f39c12;
}

.friend-item.blocked {
  opacity: 0.5;
}

.friend-item.blocked .friend-status {
  color: #e74c3c;
}

.friend-avatar {
  position: relative;
  margin-right: 10px;
}

.friend-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.online-status {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #95a5a6;
  border: 2px solid #599ce9;
}

.friend-item.online .online-status {
  background-color: #2ecc71;
}

.friend-info {
  flex: 1;
  min-width: 0;
}

.friend-name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.friend-status {
  font-size: 0.8em;
  margin-top: 2px;
  color: #666;
}

.unread-count {
  background-color: #e74c3c;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.7em;
}

.no-friends-in-group {
  padding: 10px;
  text-align: center;
  color: #999;
  font-size: 0.9em;
}

.no-friends {
  padding: 15px;
  text-align: center;
  color: #666;
}

.refresh-btn {
  padding: 4px 8px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8em;
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.error-message {
  padding: 15px;
  color: #e74c3c;
  text-align: center;
  font-size: 0.9em;
}

.error-message button {
  margin-top: 8px;
  padding: 4px 8px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.8em;
}

/* 添加好友对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.add-friend-dialog {
  background-color: white;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  font-size: 1.2em;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5em;
  cursor: pointer;
  color: #666;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1em;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-footer button {
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
}

.cancel-btn {
  background-color: #f0f0f0;
  border: 1px solid #ddd;
}

.confirm-btn {
  background-color: #4a90e2;
  color: white;
  border: none;
}

.confirm-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .friend-sidebar {
    width: 100%;
    height: auto;
    max-height: 50vh;
  }

  .group-friends {
    max-height: 150px;
  }

  .add-friend-dialog {
    width: 90%;
  }
}
.delete-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 1.2em;
  cursor: pointer;
  padding: 0 5px;
  margin-left: 5px;
  opacity: 0;
  transition: opacity 0.2s;
}

.friend-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  color: #f56c6c;
}
</style>